package cn.dida.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Logistics;
import cn.dida.model.Pageable;
import cn.dida.model.UserSession;
import cn.dida.service.LogisticsService;

/**
 * <p>承运方管理</p>
 * @author lisha
 * @date 2016-11-09 12:05
 * */
@Controller
public class LogisticsController extends BaseController {
	
	@Autowired
	private LogisticsService logisticsService;
	
	/**
	 * 增加承运方
	 * @param request
	 * @param logistics 承运方实体类
	 * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
	 * @throws Exception
	 */
	@ResponseBody
    @PostMapping("/logisticscompany")
    public HttpResponseBodyWrapper add(HttpServletRequest request, @RequestBody Logistics logistics) throws Exception {
        
        UserSession userSession = getUserSession(request);
        logistics.setCompanyId(userSession.getCompanyId());
        logistics.setName(StringUtils.trimToNull(logistics.getName()));
        logistics.setWebsite(StringUtils.trimToNull(logistics.getWebsite()));
        logistics.setcAdmin(userSession.getAccount());
        logistics.setuAdmin(userSession.getAccount());

        if (logistics.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入公司名称");
        }
        if (logistics.getWebsite() == null) {
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入公司官网");
        }
        
        Boolean flag = logisticsService.isExistsActivity(userSession.getCompanyId(), logistics.getName());
        if(flag){
        	throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【"+logistics.getName()+"】的承运方");
        }

        Boolean result = logisticsService.insertLogistics(logistics);
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 修改承运方
	 * @param request
	 * @param logistics 承运方实体类
	 * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
	 * @throws Exception
	 */
	@ResponseBody
    @PutMapping("/logisticscompany/{id}")
    public HttpResponseBodyWrapper update(HttpServletRequest request, @RequestBody Logistics logistics) throws Exception {
		UserSession userSession = getUserSession(request);
        logistics.setName(StringUtils.trimToNull(logistics.getName()));
        //logistics.setWebsite(StringUtils.trimToNull(logistics.getWebsite()));
		logistics.setCompanyId(userSession.getCompanyId());
		logistics.setuAdmin(userSession.getAccount());
        if (logistics.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入公司名称");
        }
        if (logistics.getWebsite() == null) {
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入公司官网");
        }
        
        Logistics temp = logisticsService.getLogisticsById(userSession.getCompanyId(), "", logistics.getId());
        if(temp != null && !(temp.getName().equals(logistics.getName()))){
        	if(logisticsService.isExistsActivity(userSession.getCompanyId(), logistics.getName())){
        		throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【"+logistics.getName()+"】的承运方");
        	}
        }
        
        Boolean result = logisticsService.updateLogistics(userSession.getCompanyId(),logistics);
        
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 删除承运方
	 * @param request
	 * @param id 承运方id
	 * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
	 * @throws Exception
	 */
	@ResponseBody
    @DeleteMapping("/logisticscompany/{id}")
    public HttpResponseBodyWrapper deleteBrand(HttpServletRequest request, @PathVariable int id) throws Exception {
		 UserSession userSession = getUserSession(request);
		 Logistics logistics = logisticsService.getLogisticsById(userSession.getCompanyId(),"", id);
		 Boolean result = false;
		 if(logistics != null){
			 result = logisticsService.deleteLogisticsByNumber(id);
		 }
        return new HttpResponseBodyWrapper(result);
    }
	
	/**
	 * 承运方列表
	 * @param request
	 * @param name 承运方名称
	 * @param page 分页游标
	 * @return ModelAndView 承运方列表页面
	 * @throws Exception
	 */
	@GetMapping("/logisticscompany")
    public ModelAndView list(HttpServletRequest request, String name, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        name = StringUtils.trimToEmpty(name);
        //name = new String(name.getBytes("iso-8859-1"),"utf-8");//查询条件中文转码
        Pageable<Logistics> logisticsList = logisticsService.queryLogistics(userSession.getCompanyId(),name, page);

        model.put("logisticsList", logisticsList);
        model.put("name", name);
        return new ModelAndView("logistics_list").addAllObjects(model);
    }
	/**
	 * 获取承运方详情
	 * @param request
	 * @param name 承运方名称
	 * @param id 承运方id
	 * @return HttpResponseBodyWrapper 封装单个承运方实体数据
	 * @throws Exception
	 */
	@ResponseBody
    @GetMapping("/logisticscompany/{name}/{id}")
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request, @PathVariable String name,@PathVariable int id) throws Exception {
		name = URLDecoder.decode(name,"utf-8");
		UserSession userSession = getUserSession(request);
        Logistics logistics = logisticsService.getLogisticsById(userSession.getCompanyId(),name, id);
        return new HttpResponseBodyWrapper(logistics);
    }
	
	/**
	 * 获取承运方列表，兑奖列表中填写配送信息使用
	 * @param request
	 * @param state 状态:（1正常，0否）
	 * @return HttpResponseBodyWrapper 封装承运方列表数据
	 * @throws Exception
	 */
	@ResponseBody
    @GetMapping(value = "/logisticscompany", produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpResponseBodyWrapper getlogistics(HttpServletRequest request, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        List<Logistics> logisticsList = logisticsService.queryLogistics(state);
        model.put("logisticsList", logisticsList);
        return new HttpResponseBodyWrapper(logisticsList);
    }
}
